package com.tangdada.whacmole;

import android.content.res.AssetManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;

import com.support.libs.App;
import com.support.libs.utils.graphics.ImageCache;

import java.io.InputStream;

/**
 * Created by Administrator on 2018/4/13 0013.
 */

public class ImageUtil {

    public static ImageCache imageCache;

    public static Bitmap loadBitmap(String assetName) {
        return loadBitmap(assetName, false);
    }

    public static Bitmap loadBitmap(String assetName,boolean isScaleY) {
        if (imageCache == null) {
            imageCache = new ImageCache(App.sInstance, "game");
        }
        try {
            Bitmap bitmap = imageCache.getBitmapFromDiskCache(assetName);
            if(bitmap == null || bitmap.isRecycled()){
                Resources resources = App.sInstance.getResources();
                AssetManager assetManager = resources.getAssets();
                InputStream is = assetManager.open(assetName);
                bitmap = BitmapFactory.decodeStream(is);
                bitmap = changeImageSize(bitmap,isScaleY);
                imageCache.addBitmapToCache(assetName,bitmap, resources);
            }
            return bitmap;
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return null;
    }

    private static Bitmap changeImageSize(Bitmap img, boolean isScaleY) {

        Matrix matrix = new Matrix();
        float scale = isScaleY ? GameView.sScale_Y:GameView.sScale_X;
        matrix.postScale(scale, scale);

        Bitmap resizedBitmap = Bitmap.createBitmap(img, 0, 0, (int)img
                .getWidth(), (int)img.getHeight(), matrix, true);
        img.recycle();
        return resizedBitmap;
    }

}
